/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ServerChooser.java
 *
 * Created on May 29, 2011, 12:19:10 PM
 */
package src.client.ui.initgame;

import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JOptionPane;
import src.client.Server;
import src.client.ui.StartGame;

/**
 *  A Dialog which allows you to choose the server to which you want to
 * connect. If no address was input, uses the default URL which is:
 * http://localhost:8080/axis2/services/MonopolyGame
 * @author Shachar Butnaro and Omer Shenhar
 */
public class ServerChooser extends javax.swing.JDialog {

    /** Creates new form ServerChooser */
    public ServerChooser(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addressTextArea = new javax.swing.JFormattedTextField();
        submitButton = new javax.swing.JButton();
        instructionsLable = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        submitButton.setText("submit");
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });

        instructionsLable.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        instructionsLable.setText("leave blank to use localhost:8080");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(addressTextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(submitButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(instructionsLable)))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(instructionsLable)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addressTextArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(submitButton))
                .addContainerGap(173, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
        String url =addressTextArea.getText();
        try {
            URI testURI=new URI(url);
            OK(url);
        } catch (URISyntaxException ex) {
           if(url.equals(""))
           {
               OK(url);           
           }
           else
           {
               NOTOK(url+" is invalid");
           }
        }
        catch(ExceptionInInitializerError e)
        {
            NOTOK("An error occured while attempting connection");
        }
    }//GEN-LAST:event_submitButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ServerChooser dialog = new ServerChooser(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField addressTextArea;
    private javax.swing.JLabel instructionsLable;
    private javax.swing.JButton submitButton;
    // End of variables declaration//GEN-END:variables

    /**
     * Check the URL. if connection is possible, dispose of the Dialog,
     * and start the game selection window.
     * @param url 
     */
    private void OK(String url) {
        boolean hasConnection;
        try
        {
            hasConnection=Server.getInstance().setAdderss(url);
        }
        catch(Exception e)
        {
            NOTOK("An error occured: try again.");   
            return;
        }
        catch(Error  e)
        {
            NOTOK("An error occured: try again.");   
            return;
        }
        if(hasConnection)
        {
            this.dispose();
            StartGame.StartGame();
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Could not start connection to given URL", "Server Communication Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * If connection is not available, issue a proper error message.
     * @param message 
     */
    private void NOTOK(String message) {
                    JOptionPane.showMessageDialog(this, message, "Server Communication Error", JOptionPane.ERROR_MESSAGE);
    }
}